package com.gui.universe;

import com.data.Universe;
import com.gooddies.texteditors.DefaultIntegerTextField;
import com.gooddies.texteditors.DefaultTextField;
import com.swingson.SwingsonGuiBuilder;
import java.awt.Frame;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JDialog;

public class UniverseEditorDialog extends JDialog {

    private final Universe universe;
    private final DefaultIntegerTextField positionField = new DefaultIntegerTextField(0, 100);
    private final DefaultIntegerTextField indexField = new DefaultIntegerTextField(0, 100);
    private final DefaultIntegerTextField subNetField = new DefaultIntegerTextField(0, 100);
    private final DefaultIntegerTextField portField = new DefaultIntegerTextField(0, 65536);
    private final DefaultTextField ipField = new DefaultTextField();

    public UniverseEditorDialog(Frame owner, Universe universe) {
        super(owner, true);
        setTitle("Universe Editor");
        setResizable(false);
        this.universe = universe;
        positionField.setValue(universe.getPosition());
        indexField.setValue(universe.getIndex());
        subNetField.setValue(universe.getSubNet());
        portField.setValue(universe.getPort());
        ipField.setText(universe.getIp());
        SwingsonGuiBuilder.createGuiFromJsonInPackage(this);
    }

    private static final String PATTERN = "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

    private boolean validateIp(String ip) {
        Pattern pattern = Pattern.compile(PATTERN);
        Matcher matcher = pattern.matcher(ip);
        return matcher.matches();
    }

    private boolean validateInput() {
        if (!validateIp(ipField.getText())) {
            ipField.showError("Please enter valid ip string");
            return false;
        }
        return true;
    }

    protected void onSave() {
        if (!validateInput()) {
            return;
        }

        universe.setIndex(indexField.getValue());
        universe.setSubNet(subNetField.getValue());
        universe.setPort(portField.getValue());
        universe.setIp(ipField.getText());
        setVisible(false);
        dispose();
    }

    protected void onCancel() {
        setVisible(false);
        dispose();
    }
}
